package com.banzhi.shop.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.PersonDetail.Person_Data;
import com.banzhi.shop.model.CallBack.InputPicturesCallBack;
import com.banzhi.shop.model.CallBack.PersonDetailCallBack;
import com.banzhi.shop.model.IInputPictureModel;
import com.banzhi.shop.model.IPersonDetailModel;
import com.banzhi.shop.model.Impl.InputPictureImpl;
import com.banzhi.shop.model.Impl.PersonDetailImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.BitmapUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.PermissionsChecker;
import com.banzhi.shop.utils.PersonDetailUtils;
import com.banzhi.shop.utils.TemplatePopupwindowUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.banzhi.shop.view.CircleImageView;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * 个人资料
 */
public class PersonDetailActivity extends BaseActivity implements View.OnClickListener, PersonDetailCallBack, InputPicturesCallBack {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 姓名
     */
    private TextView tvname;
    /**
     * 保存
     */
    private Button btnsave;
    /**
     * 性别
     */
    private TextView tvxingbie;
    /**
     * 生日
     */
    private TextView tvbirthday;
    /**
     * 性别布局
     */
    private LinearLayout llxingbie;
    /**
     * 昵称布局
     */
    private LinearLayout llname;
    /**
     * 生日布局
     */
    private LinearLayout llbirthday;
    /**
     * 头像布局
     */
    private LinearLayout llimage;
    private CircleImageView civ_image;
    /**
     * 个人信息数据
     */
    private Person_Data data;



    private IPersonDetailModel model;
    private IInputPictureModel picmodel;
    /**
     * 裁剪后的照片文件
     */
    private File Imagefile;
    /**
     * 上传头像后返回的头像的网络地址
     */
    private String imageURL;
    private Bitmap bitmap;
    private File dir;
    /**
     * Save the path of photo cropping is completed
     */
    private Uri icon_path;
    private Uri camera_path;
    private static final int CODE_GALLERY_REQUEST = 0x1;
    private static final int CODE_CAMERA_REQUEST = 0x2;
    private static final int CROP_PICTURE_REQUEST = 0x3;

    private static final String TEMP_FILE_NAME = "temp_icon.jpg";
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_detail);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        mPermissionsChecker = new PermissionsChecker(this);
        model = new PersonDetailImpl();
        picmodel = new InputPictureImpl();
        if (!"".equals(MyApp.loginMessage.getString("personGender", ""))) {
            showViews();
        } else {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getData(this);
        }
    }
    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        tvname = (TextView) findViewById(R.id.tv_name);
        btnsave = (Button) findViewById(R.id.btn_save);
        tvxingbie = (TextView) findViewById(R.id.tv_xingbie);
        tvbirthday = (TextView) findViewById(R.id.tv_birthday);
        civ_image = (CircleImageView) findViewById(R.id.civ_image);
        llxingbie = (LinearLayout) findViewById(R.id.ll_xingbie);
        llname = (LinearLayout) findViewById(R.id.ll_name);
        llbirthday = (LinearLayout) findViewById(R.id.ll_birthday);
        llimage = (LinearLayout) findViewById(R.id.ll_image);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        llxingbie.setOnClickListener(this);
        btnsave.setOnClickListener(this);
        llname.setOnClickListener(this);
        llbirthday.setOnClickListener(this);
        llimage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_xingbie:
                showxingbiePopupwindow();
                break;
            case R.id.ll_name:
                shownamePopupwindow();
                break;
            case R.id.ll_birthday:
                PersonDetailUtils.showbrithdayPopwidow(this, tvbirthday);
                break;
            case R.id.ll_image:
                showImagePopwindow();
                break;
            case R.id.btn_save:

                if (!ASUtils.isCanUse(tvname.getText().toString().trim())) {
                    ToastUtils.makeToastShort("请先输入昵称");
                } else if (!ASUtils.isCanUse(tvbirthday.getText().toString().trim())) {
                    ToastUtils.makeToastShort("请先输入生日");
                } else if (!ASUtils.isCanUse(tvxingbie.getText().toString().trim())) {
                    ToastUtils.makeToastShort("请先输入性别");
                } else {
                    String[] str = tvbirthday.getText().toString().trim().split("-");
                    String garden = null;
                    if ("男".equals(tvxingbie.getText().toString().trim())) {
                        garden = "1";
                    } else if ("女".equals(tvxingbie.getText().toString().trim())) {
                        garden = "2";
                    }
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    if (ASUtils.isCanUse(imageURL)) {
                        model.ChangeData(imageURL, tvname.getText().toString().trim(), str[0], str[1], str[2], garden, this);
                    } else {
                        model.ChangeData(MyApp.loginMessage.getString("personAvatar", ""), tvname.getText().toString().trim(), str[0], str[1], str[2], garden, this);
                    }
                }
                break;
        }
    }


    private void showViews() {
        tvname.setText(MyApp.loginMessage.getString("personNickname", ""));
        if (ASUtils.isCanUse(MyApp.loginMessage.getString("personAvatar", ""))) {
            Picasso.with(this).load(MyApp.loginMessage.getString("personAvatar", "")).placeholder(R.mipmap.zhanweitu2).into(civ_image);
        }
        tvbirthday.setText(MyApp.loginMessage.getString("personBirth", ""));
        if ("1".equals(MyApp.loginMessage.getString("personGender", ""))) {
            tvxingbie.setText("男");
        } else if ("2".equals(MyApp.loginMessage.getString("personGender", ""))) {
            tvxingbie.setText("女");
        }
    }

    /**
     * @param object 修改个人信息成功
     */
    @Override
    public void onChangeDataSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        model.getData(this);
    }

    /**
     * @param object 修改个人信息失败
     */
    @Override
    public void onChangeDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 获取个人信息成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        data = (Person_Data) object;
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("personNickname", data.getNickname());
        editor.putString("personAvatar", data.getAvatar());
        editor.putString("personBirth", data.getBirth());
        editor.putString("personGender", data.getGender());
        editor.apply();
        showViews();

    }

    /**
     * @param object 获取个人信息失败
     */
    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 输入昵称
     */
    private void shownamePopupwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(PersonDetailActivity.this).inflate(R.layout.popupwindow_input_name, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        final EditText etname = (EditText) contentView.findViewById(R.id.et_name);
        TextView tvsave = (TextView) contentView.findViewById(R.id.tv_save);
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);

        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        if (ASUtils.isCanUse(tvname.getText().toString().trim())) {
            etname.setText(tvname.getText().toString().trim());
        }
        tvsave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ASUtils.isCanUse(etname.getText().toString().trim())) {
                    ToastUtils.makeToastShort("请先输入昵称");
                } else {
                    tvname.setText(etname.getText().toString().trim());
                    popWindow.dismiss();
                }
            }
        });

        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /**
     * 选择性别
     */
    private void showxingbiePopupwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(PersonDetailActivity.this).inflate(R.layout.popupwindow_choice_xingbie, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
//        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        //设置各个控件的点击响应
        LinearLayout llmen = (LinearLayout) contentView.findViewById(R.id.ll_men);
        LinearLayout llwomen = (LinearLayout) contentView.findViewById(R.id.ll_women);
        final ImageView ivmen = (ImageView) contentView.findViewById(R.id.iv_men);
        final ImageView ivwomen = (ImageView) contentView.findViewById(R.id.iv_women);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        if ("男".equals(tvxingbie.getText().toString().trim())) {
            ivmen.setImageResource(R.mipmap.xz);
            ivwomen.setImageResource(R.mipmap.wxz);
        } else {
            ivmen.setImageResource(R.mipmap.wxz);
            ivwomen.setImageResource(R.mipmap.xz);
        }
        llmen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivmen.setImageResource(R.mipmap.xz);
                ivwomen.setImageResource(R.mipmap.wxz);
                tvxingbie.setText("男");
                popWindow.dismiss();
            }
        });
        llwomen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivmen.setImageResource(R.mipmap.wxz);
                ivwomen.setImageResource(R.mipmap.xz);
                tvxingbie.setText("女");
                popWindow.dismiss();
            }
        });
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    /**
     * 选择头像
     */
    private void showImagePopwindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_image, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);

        Button btnCamera = (Button) contentView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) contentView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) contentView.findViewById(R.id.btn_camera_pop_cancel);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_camera_pop_camera:
                        //检查权限(6.0以上做权限判断)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                                requestPermissions(PERMISSIONS, 1000);
                            } else {
                                openCamera();
                            }
                        } else {
                            openCamera();
                        }
                        break;
                    case R.id.btn_camera_pop_album:
                        //检查权限(6.0以上做权限判断)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (mPermissionsChecker.lacksPermissions(PERMISSIONS[1])) {
                                requestPermissions(new String[]{PERMISSIONS[1]}, 1100);
                            } else {
                                selectFromAlbum();
                            }
                        } else {
                            selectFromAlbum();
                        }

                        break;
                    case R.id.btn_camera_pop_cancel:

                        break;

                }
                popWindow.dismiss();
            }
        };

        btnCamera.setOnClickListener(listener);
        btnAlbum.setOnClickListener(listener);
        btnCancel.setOnClickListener(listener);

        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 打开系统相机
     */
    private void openCamera() {
        dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(getApplicationContext(),
                    getPackageName() + ".fileprovider", new File(dir, TEMP_FILE_NAME));
            camera_path = FileProvider.getUriForFile(getApplicationContext(),
                    getPackageName() + ".fileprovider", new File(dir, "camera_pic.jpg"));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
            camera_path = Uri.fromFile(new File(dir, "camera_pic.jpg"));
        }
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, camera_path);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intentFromCapture.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);

    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(PersonDetailActivity.this,
                    getPackageName() + ".fileprovider", new File(dir, TEMP_FILE_NAME));
            camera_path = FileProvider.getUriForFile(PersonDetailActivity.this,
                    getPackageName() + ".fileprovider", new File(dir, "camera_pic.jpg"));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
            camera_path = Uri.fromFile(new File(dir, "camera_pic.jpg"));
        }
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        Intent intentFromGallery = new Intent();
//        intentFromGallery.setType("image/*");
//        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, CODE_GALLERY_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                cropImage(data.getData(), 450, 450, CROP_PICTURE_REQUEST);
                break;
            case CODE_CAMERA_REQUEST:

                cropImage(camera_path, 450, 450, CROP_PICTURE_REQUEST);
                break;
            case CROP_PICTURE_REQUEST:
                bitmap = decodeUriAsBitmap(icon_path);
                Imagefile = BitmapUtils.saveBitmapFile(BitmapUtils.comBitmap(bitmap, 0.2f), "camera");
                picmodel.getData(Imagefile, null, this);
                break;

        }

        super.onActivityResult(requestCode, resultCode, data);


    }

    /**
     * According to the incoming a length-width ratio began to cut out pictures
     *
     * @param uri Image source
     */
    private void cropImage(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // Set the cutting
        intent.putExtra("crop", "true");
        // aspectX , aspectY :In proportion to the width of high
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX , outputY : High cutting image width
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, icon_path);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            addurlPram(this, intent, camera_path, icon_path);
        }
        startActivityForResult(intent, requestCode);
    }

    private void addurlPram(Activity activity, Intent intent, Uri... uris) {
        List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            for (Uri uri : uris) {
                activity.grantUriPermission(packageName, uri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * @param object 上传图片成功
     */
    @Override
    public void inputSuccess(Object object, String type) {
        JSONObject jsonObject = (JSONObject) object;
        imageURL = jsonObject.optString("res");
        if (ASUtils.isCanUse(imageURL)) {
            Picasso.with(this).load(imageURL).placeholder(R.mipmap.zhanweitu2).into(civ_image);
        } else {
            civ_image.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
        }
    }


    /**
     * @param object 上传图片失败
     */
    @Override
    public void inputError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 1000:
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(PersonDetailActivity.this, "当前功能缺失必要权限", "请手动开启");
                } else {
                    openCamera();
                }
                break;
            case 1100:
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS[1])) {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(PersonDetailActivity.this, "当前功能缺失必要权限", "请手动开启");
                } else {
                    selectFromAlbum();
                }
                break;
        }
    }

}
